package com.doujiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doujiang.domain.Favorite;
import com.doujiang.mapper.FavoriteMapper;
import com.doujiang.service.zzqIFavoriteService;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 收藏/想看Service业务层处理
 * 
 * @author 王伟舰
 * @date 2025-07-19
 */
@Service
public class zzqFavoriteServiceImplZzq extends ServiceImpl<FavoriteMapper, Favorite> implements zzqIFavoriteService
{
    @Override
    public boolean saveFavorite(Favorite favorite) {
        return save(favorite);
    }

    @Override
    public boolean updateFavoriteType(Long userId, Long movieId, Integer type) {
        try {
            // 物理删除所有相关记录，彻底避免唯一键冲突
            baseMapper.deleteRealByUserAndMovie(userId, movieId);

            // 创建新记录
            Favorite favorite = new Favorite();
            favorite.setUserId(userId);
            favorite.setMovieId(movieId);
            favorite.setType(type);
            favorite.setDeleted(0L);
            return save(favorite);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean removeFavoritePhysically(Long userId, Long movieId) {
        try {
            int rows = baseMapper.deleteRealByUserAndMovie(userId, movieId);
            return rows > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Favorite getFavoriteByUserAndMovie(Long userId, Long movieId) {
        return lambdaQuery().eq(Favorite::getUserId, userId)
                .eq(Favorite::getMovieId, movieId)
                .eq(Favorite::getDeleted, 0L) // 只查询未软删除的记录
                .one();
    }

    @Override
    public List<Favorite> getUserWatchlist(Long userId) {
        return lambdaQuery().eq(Favorite::getUserId, userId)
                .in(Favorite::getType, 1, 2) // 1=想看, 2=已看
                .eq(Favorite::getDeleted, 0L) // 只查询未软删除的记录
                .orderByDesc(Favorite::getCreatedAt)
                .list();
    }

    @Override
    public List<Favorite> getUserWatchlistByType(Long userId, Integer type) {
        return lambdaQuery().eq(Favorite::getUserId, userId)
                .eq(Favorite::getType, type)
                .eq(Favorite::getDeleted, 0L) // 只查询未软删除的记录
                .orderByDesc(Favorite::getCreatedAt)
                .list();
    }

}
